package case30

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-playground/validator/v10"
	"net/http"
)

func Test() {

	fmt.Println("🎯示例三十：验证器-xxx")
	r := gin.Default()

	// 注册验证器
	if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
		v.RegisterValidation("phone", phoneValidator)
	}

	r.POST("/user", func(c *gin.Context) {
		var req UserRequest
		if err := c.ShouldBindJSON(&req); err != nil {
			if validationErrors, ok := err.(validator.ValidationErrors); ok {
				errors := make(map[string]string)
				for _, fieldError := range validationErrors {
					fieldName := fieldError.Field()
					switch fieldError.Tag() {
					case "required":
						errors[fieldName] = "该字段为必填项"
					case "phone":
						errors[fieldName] = "手机号格式不正确"
					default:
						errors[fieldName] = "字段验证失败"
					}
				}
				c.JSON(http.StatusBadRequest, gin.H{
					"error":   "参数验证失败",
					"details": errors,
				})
				return
			}
			// 其他类型的错误
			c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
			return
		}

		c.JSON(http.StatusOK, gin.H{
			"message": "成功",
			"data":    req,
		})
	})

	r.Run(":60000")

}

type UserRequest struct {
	Phone string `json:"phone" binding:"required,phone"`
}

// 手机号验证器
var phoneValidator validator.Func = func(fl validator.FieldLevel) bool {
	phone, ok := fl.Field().Interface().(string)
	if !ok {
		return false
	}
	// 简单的手机号格式验证
	return len(phone) == 11 && phone[0] == '1'
}
